<?php
namespace Api\Controller;
use Think\Controller;
class CommissionController extends CommonController {

    //团队分红首页
    public function team_index()
    {
        $list['member'] = getMember(session('wid'),I('openid'));
        //我的团员
        $list['myteam'] = M('member')
                    ->alias('m')
                    ->join('tp_card_log l on l.openid = m.openid')
                    ->where(['team_leader'=>$list['member']['mid'],'end_time'=>['GT', date('Y-m-d H:i:s', time())],'is_pay'=>1])
                    ->count();
        //计算未提现的分红
        $list['commission_wite'] = M('commission')->where(['mid'=>$list['member']['mid'],'is_withdraw'=>0,'mold'=>1])->sum('money')?:0;
        //计算提现的分红
        $list['commission_wite2'] = M('commission')->where(['mid'=>$list['member']['mid'],'is_withdraw'=>1,'mold'=>1])->sum('money')?:0;
        //提现笔数
        $list['withdraw_count'] = M('commission_putmoney')->where(['openid'=>$list['member']['openid'],'type'=>1])->count();
        //团队二维码之类的问题
        //是队长
        if($list['member']['is_team_leader']){
            $leaderid = $list['member']['mid'];
        }
        //不是队长
        if($list['member']['team_leader']){
            $leaderid = $list['member']['team_leader'];
            $list['leader'] = getMemberByMid(session('wid'),$leaderid);
        }

        $list['team_set'] = M('commission_team')->where(['leaderid'=>$leaderid,'status'=>1])->find();
        $this->ajaxReturn($list);
    }

    //获得分红订单
    public function getBonusOrder()
    {
        $member  = getMember(session('wid'),I('openid'));
        $list = M('commission')->alias('c')->join('tp_member m on m.mid =c.fmid')->where(['c.mid'=>$member['mid'],'mold'=>1])->select();
        $this->ajaxReturn($list);
    }

    //获取团队分红提现页面
    public function getMyTeamWithdraw()
    {
        $wid    = session('wid');
        $openid = I('openid');
        $list   = [];
        $info   = M('member')->where(['openid'=>$openid, 'wid' => $wid])->find();
        if(!$info){
            return false;
        }

        //计算未提现的佣金
        $commission_wite = M('commission')->where(['mid'=>$info['mid'],'is_withdraw'=>0,'mold'=>1])->sum('money');
        $list['wite_money'] = $commission_wite?$commission_wite:0;
        //平台抽取比例
        $list['ratio']      = M('wechat')->where(['wid' => $wid])->getField('team_withdraw');
        $list['ratio_money'] = round($list['ratio'] * $list['wite_money'] / 100, 2);

        $this->ajaxReturn($list);
    }

    //团队分红我的团员
    public function getMyteam()
    {
        $member = getMember(session('wid'),I('openid'));
        $list['myteam'] = M('member')
            ->alias('m')
            ->join('tp_card_log l on l.openid = m.openid')
            ->where(['team_leader'=>$member['mid'],'end_time'=>['GT', date('Y-m-d H:i:s', time())],'is_pay'=>1])
            ->select();
        $list['myteam_count'] = count($list['myteam']);
        $list['mine'] = $member;
        //计算分红
        foreach ($list['myteam'] as $k => $v) {
            $arr = M('commission')->where(['mid' => $member['mid'],'fmid' => $v['mid'], 'wid' => session('wid'), 'mold' => 1])->select();
            if ($arr) {
                $m_num = 0;
                foreach ($arr as $key => $value) {
                    $m_num += $value['money'];
                }
                $list['myteam'][$k]['fenhong_money'] = $m_num;
            } else {
                $list['myteam'][$k]['fenhong_money'] = 0;
            }
        }
        $this->ajaxReturn($list);
    }


    //团队管理
    public function  team_mange()
    {
        $member = getMember(session('wid'),I('openid'));
        //获取团队信息
        if(I('type') == 'get'){
            $team = M('commission_team')->where(['leaderid'=>$member['mid'],'status'=>1])->find();
            $this->ajaxReturn($team);
        }else{
        //修改团队信息
            $data['team_name'] = I('team_name');
            $data['leader2_commission'] = I('leader2_commission');
            $re = M('commission_team')->where(['id'=>I('id')])->save($data);
            if($re){
                $arr = array("err_code"=>0,"err_msg"=>"修改成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"未修改任何信息！");
                $this->ajaxReturn($arr);
            }
        }
    }

    public function getCommDetail () {
        $list = getMember(session('wid'),I('openid'));
        $this->ajaxReturn($list);
    }

    //二级分销下线
    public function getLv () {
        $wid    = session('wid');
        $openid = I('openid');
        $list   = [];
        $info   = M('member')->where(['openid'=>$openid, 'wid' => $wid])->find();
        if(!$info){
            return false;
        }
        $myMid  = $info['mid'];
        //一级分销信息
        $lv_one = M('member')->where(['agent' => $myMid, 'wid' => $wid])->select();
        //二级分销信息
        $lv_two = [];
        $sTow_c = [];
        if ($lv_one) {
            foreach ($lv_one as $k => $v) {
                $sTwo   = M('member')->where(['agent' => $v['mid'], 'wid' => $wid])->select();
                $lv_two = array_merge($sTow_c, $sTwo);
                $sTow_c = $sTwo;
            }
        }
        $list['lv_one'] = $lv_one;
        $list['lv_two'] = $lv_two;
        //佣金计算
        foreach ($list as $key => $value) {
            if ($value) {
                foreach ($value as $k => $v) {
                    $oneArr = M('commission')->where(['wid' => $wid, 'mid' => $myMid, 'fmid' => $v['mid']])->select();
                    if ($oneArr) {
                        $one_money = 0.00;
                        foreach ($oneArr as $kk => $vv) {
                            $one_money += $vv['money'];
                        }
                        $list[$key][$k]['comm_money'] = $one_money;
                    } else {
                        $list[$key][$k]['comm_money'] = 0.00;
                    }
                }
            }
        }
        $this->ajaxReturn($list);
    }

    //申请成为队长。队长满足条件时申请，不是付费申请逻辑
    public function become_leader()
    {
        $wid = session('wid');
        $openid = I('openid');
        $postV = $_POST;
        $time =date('Y-m-d H:i:s', time());
        $weahct = M('wechat')->where(['wid'=>$wid])->find();
        if(!$weahct){
            $this->ajaxReturn(['err_code' => 401, 'err_msg' => '网络忙！']);
        }
        foreach ($postV as $key => $value) {
            if(!is_numeric($value) && empty($value)){

                $arr = array("err_code"=>401,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        //团队开通同城卡的人数
        $member = getMember($wid,$openid);
        //是否已经申请队长
        $team = M('commission_team')->where(['leaderid'=>$member['mid']])->find();
        if($team){
            $this->ajaxReturn(["err_code"=>401,"err_msg"=>"已申请过队长"]);
        }

        //判断上级是否已经有队长
        if($member['team_leader']){
            $this->ajaxReturn(['err_code' => 200, 'err_msg' => '团队内已有队长，是否脱离团队重新创建团队？']);
        }
        if(!$member['has_card']){
            $this->ajaxReturn(['err_code' => 401, 'err_msg' => '请开通同城卡']);
        }
        $sql = "select count(*) as c
                from
                  tp_member m
                left join
                  tp_card_log l on l.openid = m.openid
                where
                    FIND_IN_SET({$member['mid']},m.path)
                    and l.wid ={$wid}
                    and l.is_pay =1
                    and end_time > '{$time}'
                    limit 0,1";
        $re = M()->query($sql);
        $count = $re[0]['c'];
        //人数不达标
        if($count< $weahct['leader_people']){
            $arr = array("err_code"=>400, "err_msg"=>"团队人数不达标！");
            $this->ajaxReturn($arr);
        }
        //判断佣金金额是否达标
        $map['mid'] = $member['mid'];
        $money = M('commission')->where($map)->sum('money');
        if(intval($money)<$weahct['leader_commission']){
            $arr = array("err_code"=>400, "err_msg"=>"佣金额度不符合要求！");
            $this->ajaxReturn($arr);
        }
        //已达标添加记录
        $data['leaderid'] = $member['mid'];//队长id
        $data['team_name'] = I('team_name');//团队名称
        $data['wid'] =session('wid');
        $data['wx'] = I('wx');//微信号
        $data['name'] = I('name');//姓名
        $data['tel'] = I('tel');//电话
        $data['type'] = 0; //0达到条件 1花钱
        $data['create_time'] = $time;
        $data['status'] = 0;
        $re = M('commission_team')->add($data);
        if($re){
            //发送模板消息
            sendShenpiMessage($re,'leader');
            $arr = array("err_code"=>0, "err_msg"=>"申请成功，请等待审核！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400, "err_msg"=>"团队人数不达标！");
            $this->ajaxReturn($arr);
        }
    }

    //申请成为队长。队长满足条件时申请，不是付费申请逻辑
    public function become_leader2()
    {
        $wid = session('wid');
        $openid = I('openid');
        $postV = $_POST;
        $time =date('Y-m-d H:i:s', time());
        $weahct = M('wechat')->where(['wid'=>$wid])->find();
        if(!$weahct){
            $this->ajaxReturn(['error' => 400, 'msg' => '网络忙！']);
        }
        foreach ($postV as $key => $value) {
            if(!is_numeric($value) && empty($value)){

                $arr = array("err_code"=>401,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        //团队开通同城卡的人数
        $member = getMember($wid,$openid);
        //判断上级是否已经有队长
        if(!$member['has_card']){
            $this->ajaxReturn(['err_code' => 401, 'err_msg' => '请开通同城卡']);
        }
        $sql = "select count(*) as c
                from
                  tp_member m
                left join
                  tp_card_log l on l.openid = m.openid
                where
                    FIND_IN_SET({$member['mid']},m.path)
                    and l.wid ={$wid}
                    and l.is_pay =1
                    and end_time > '{$time}'
                    limit 0,1";
        $re = M()->query($sql);
        $count = $re[0]['c'];
        //人数不达标
        if($count< $weahct['leader_people']){
            $arr = array("err_code"=>400, "err_msg"=>"团队人数不达标！");
            $this->ajaxReturn($arr);
        }
        //判断佣金金额是否达标
        $map['mid'] = $member['mid'];
        $money = M('commission')->where($map)->sum('money');
        if(intval($money)<$weahct['leader_commission']){
            $arr = array("err_code"=>400, "err_msg"=>"佣金额度不符合要求！");
            $this->ajaxReturn($arr);
        }
        //已达标添加记录
        $data['leaderid'] = $member['mid'];//队长id
        $data['team_name'] = I('team_name');//团队名称
        $data['wid'] =session('wid');
        $data['wx'] = I('wx');//微信号
        $data['name'] = I('name');//姓名
        $data['tel'] = I('tel');//电话
        $data['type'] = 0; //0达到条件 1花钱
        $data['create_time'] = $time;
        $data['status'] = 0;
        $re = M('commission_team')->add($data);
        if($re){
            //发送模板消息
            sendShenpiMessage($re,'leader');
            $arr = array("err_code"=>0, "err_msg"=>"申请成功，请等待审核！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400, "err_msg"=>"团队人数不达标！");
            $this->ajaxReturn($arr);
        }
    }

    //花钱成为队长调起支付
    public function getPayOrder()
    {
        $time =date('Y-m-d H:i:s', time());
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];
        $openid = I('openid');
        $member = getMember(session('wid'),$openid);

        //已达标添加记录
        $data['leaderid'] = $member['mid'];//队长id
        $data['team_name'] = I('team_name');//团队名称
        $data['wid'] =session('wid');
        $data['wx'] = I('wx');//微信号
        $data['name'] = I('name');//姓名
        $data['tel'] = I('tel');//电话
        $data['out_trade_no'] = $this->build_order_no();
        $data['create_time'] = $time;
        $data['status'] = 0;
        $data['type'] = 1;//0达到条件 1花钱
        $data['price'] = $wechat['leader_money'];
        M('commission_team')->add($data);


        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/team_leader");
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();

        $data['remark'] = "智联同城";
        $data['title'] = '申请成为队长';

        $input->SetBody($data['remark']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['price']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage().$data['pay_money']);
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg'].$data['pay_money']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }

        echo $jsApiParameters;
    }

    //佣金提现页面数据
    public function getTakeMoneyInfo () {
        $wid    = session('wid');
        $openid = I('openid');
        $list   = [];
        $info   = M('member')->where(['openid'=>$openid, 'wid' => $wid])->find();
        if(!$info){
            return false;
        }

        //计算未提现的佣金
        $commission_wite = M('commission')->where(['mid'=>$info['mid'],'is_withdraw'=>0,'mold'=>0])->sum('money');
        $list['wite_money'] = $commission_wite?$commission_wite:0;
        //平台抽取比例
        $list['ratio']      = M('wechat')->where(['wid' => $wid])->getField('decimation_ratio');
        $list['ratio_money'] = round($list['ratio'] * $list['wite_money'] / 100, 2);

        $this->ajaxReturn($list);
    }

    //全部提现产生记录
    public function takeMoney () {
        $wid = session('wid');
        $data = $_POST;
        $data['wid'] = $wid;
        $data['type'] = 0;//0佣金， 1分红
        $data['status'] = 0;//待审核
        $data['createtime'] = date('Y-m-d H:i:s', time());
        if (!$data['wxname']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '微信号不能为空']);
        }
        if (!$data['realname']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '姓名不能为空']);
        }
        if ($data['really_money'] < 1) {
            $this->ajaxReturn(['error' => 1, 'msg' => '实际到账金额不应少于1元']);
        }
        //是否开通同城卡
        $isHaveTCared = M('card_log')->where(['wid' => $wid, 'openid' => $data['openid'],'is_pay'=>1, 'end_time' => ['gt', date('Y-m-d H:i:s', time())]])->find();
        if (!$isHaveTCared) {
            $this->ajaxReturn(['error' => 1, 'msg' => '请开通同城卡']);
        }
        //是否有未审核完的申请
        $map_1['status'] = ['in', [0, 1]];
        $map_1['openid'] = ['eq', $data['openid']];
        $map_1['wid'] = ['eq', $wid];
        $map_1['type'] = 0;
        $have_work = M('commission_putmoney')->where($map_1)->find();
        if ($have_work) {
            $this->ajaxReturn(['error' => 1, 'msg' => '已申请提现,请耐心等待']);
        }
        $row = M('commission_putmoney')->add($data);
        $row ? $this->ajaxReturn(['error' => 0, 'msg' => '申请成功']) : $this->ajaxReturn(['error' => 1, 'msg' => '网络忙~']);
    }
    //分红全部提现产生记录
    public function takeBonus () {
        $wid = session('wid');
        $data = $_POST;
        $data['wid'] = $wid;
        $data['status'] = 0;//待审核
        $data['type'] = 1;//0佣金， 1分红
        $data['createtime'] = date('Y-m-d H:i:s', time());
        if (!$data['wxname']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '微信号不能为空']);
        }
        if (!$data['realname']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '姓名不能为空']);
        }
        if ($data['really_money'] < 1) {
            $this->ajaxReturn(['error' => 1, 'msg' => '实际到账金额不应少于1元']);
        }
        //是否开通同城卡
        $isHaveTCared = M('card_log')->where(['wid' => $wid, 'openid' => $data['openid'],'is_pay'=>1, 'end_time' => ['gt', date('Y-m-d H:i:s', time())]])->find();
        if (!$isHaveTCared) {
            $this->ajaxReturn(['error' => 1, 'msg' => '请开通同城卡']);
        }
        //是否有未审核完的申请
        $map_1['status'] = ['in', [0, 1]];
        $map_1['openid'] = ['eq', $data['openid']];
        $map_1['wid'] = ['eq', $wid];
        $map_1['type'] = 1;
        $have_work = M('commission_putmoney')->where($map_1)->find();
        if ($have_work) {
            $this->ajaxReturn(['error' => 1, 'msg' => '已申请提现,请耐心等待']);
        }
        $row = M('commission_putmoney')->add($data);
        $row ? $this->ajaxReturn(['error' => 0, 'msg' => '申请成功']) : $this->ajaxReturn(['error' => 1, 'msg' => '网络忙~']);
    }
    //设置副队长
    public function set_leader2()
    {
        $leader2_openid = I('leader2_openid');//被设为副队长的openid
        $leader2 = getMember(session('wid'),$leader2_openid);
        if(I('type') == 'set'){
            if(!$leader2['has_card']){
                $this->ajaxReturn(['error' => 400, 'msg' => '未开通同城卡，无法参与分红！']);
            }
            if($leader2['is_leader2'] == 1){
                $this->ajaxReturn(['error' => 400, 'msg' => '已经设为副队长']);
            }
            if($leader2['team_leader'] == 0){
                $this->ajaxReturn(['error' => 400, 'msg' => '团队没有队长，无法设为副队长']);
            }
            //判断一下比例是否超出100%
            $team = M('commission_team')->where(['leaderid'=>$leader2['team_leader'],'status'=>1])->find();
            //判断副队长佣金比例
            if($team['leader2_commission'] == 0){
                $this->ajaxReturn(['error' => 400, 'msg' => '副队长分红比例为0，请到团队管理中设置']);
            }
            //查出团队中副队长个数
            $leader2_count = M('member')->where(['team_leader'=>$leader2['team_leader'],'is_leader2'=>1])->count();
            $leader2_rate = ($leader2_count +1)*$team['leader2_commission'];
            if($leader2_rate>=100){
                $this->ajaxReturn(['error' => 400, 'msg' => '副队长分红比例大于100%']);
            }

            $data['is_leader2'] = 1;
            $re =M('member')->where(['openid'=>$leader2_openid])->save($data);
            if($re){
                $this->ajaxReturn(['error' => 0, 'msg' => '修改成功！']);
            }else{
                $this->ajaxReturn(['error' => 400, 'msg' => '网络忙！']);
            }
        }else{
            $data['is_leader2'] = 0;
            $re =M('member')->where(['openid'=>$leader2_openid])->save($data);
            if($re){
                $this->ajaxReturn(['error' => 0, 'msg' => '修改成功！']);
            }else{
                $this->ajaxReturn(['error' => 400, 'msg' => '网络忙！']);
            }
        }

    }

    //团队分红提现记录
    public function getWithdrawList()
    {
        $map['wid'] = session('wid');
        $map['openid'] = I('openid');
        $map['type'] = 1;
        $list = M('commission_putmoney')->where($map)->order('createtime desc')->select();
        //echo M()->getLastSql();

        $arr = array(
            "err_code"=>0,
            "list"=>$list
        );
        $this->ajaxReturn($arr);

    }
}